package com.kavian.test.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库连接工具
 * 
 * @author kavian
 * 
 */
public class DBUtil {

	private Connection conn;
	private Statement stmt;

	String driver = "com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://localhost:3306/blog";
	String uName = "root";
	String uPwd = "root";

	public DBUtil() {
		this.setDriver(driver);
		this.setConnection(url, uName, uPwd);
	}

	public boolean setDriver(String driver) {
		try {
			Class.forName(driver);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean setConnection(String url, String userName, String userPWD) {
        try {
        	if(null == conn){
        		conn = DriverManager.getConnection(url, userName, userPWD);
        	}
        	if(null == stmt){
        		stmt = conn.createStatement();
        	}
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
	
    /**
     * 查询操作
     * @param sql
     * @return
     */
    public ResultSet sendQuery(String sql) {
        try {
            ResultSet m_rs = stmt.executeQuery(sql);
            return m_rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    
    /**
     * 更新操作
     * @param sql
     * @return
     */
    public int sendUpdate(String sql) {
        try {
            return stmt.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

}
